package com.cnswhy.cloud.server.core.channel.service;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cnswhy.cloud.common.core.exception.BizException;
import com.cnswhy.cloud.common.core.utils.*;
import com.cnswhy.cloud.server.core.channel.model.BaseEntity;
import com.cnswhy.cloud.server.core.channel.utils.HttpClient;
import com.cnswhy.cloud.server.core.channel.utils.SDKUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SandeService {
    //http连接超时时间
    public static int connectTimeout = 300000;
    //http响应超时时间
    public static int readTimeout = 600000;
    String merchId = "6888800017305";
    String queryUrl = "https://cashier.sandpay.com.cn/qr/api/order/query";
    String createUrl = "https://cashier.sandpay.com.cn/qr/api/order/create";
    String webCreateUrl = "https://cashier.sandpay.com.cn/gw/web/order/create";
    String unionCreateUrl = "https://cashier.sandpay.com.cn/gateway/api/order/pay";
    String agentPayUrl = "https://caspay.sandpay.com.cn/agent-main/openapi/agentpay";
    String dfQueryUrl = "https://caspay.sandpay.com.cn/agent-main/openapi/queryOrder";
    String queryBalanceUrl = "https://caspay.sandpay.com.cn/agent-main/openapi/queryBalance";
    String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyIwo8Jq6XiUSY8cMrDfTRb65QaWcPH2hITZrei3jgLIdHP3kTQjZueWhp2nQ7H9s6nD99MYSydB4YKZ5qVAoVxuwRE1fnNKOx8M3npIcr/JKtvCN5TrE1XIUyxWG3F7sPbsafN+7Gwxqh5gT4/u/zq5busBztvXh+/woiqi3EGQ1WO9+P4AtYA6nr3KoVU7hdO8Aj+6aXMjQQTtDrgH/oiAHkEMJfrQmZ6irdnxzRwQ53D/GzVieAqME/sUMeIBWiy/Uj7d2TVJZ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JjMGmL9aHHrwG9c6Y3Mww4Crib/4/7+IhBmAG9OPB9c2R2AxH0HVFaJODyLEyEHrDupG66nJonB4Xk4Gz0qt/gZklnkkZv/vE1DozV10ysFfD4wKBgQCeak5BMk5e8i7+nQ4bzipwy8AfPxO8zdSup/MO0TA/Woy8V/twZmlA1UVOYQks+ywdpWhjHQKxtMGfP75YGq5vi2yvh8uxVtX8y69ewayOosQAA3DxgvRCaGIs8bEOovdGeQty3pMG/bt+9Mp+OgU0E95m1lvc1ASxDdXEXqxVfQKBgQDe5nNisgtqTnjTTbc2Ipc/mQiBxAflNr766SuTinunduOQgdzr8dE0le32bdbs1gKTsQ0xK27FFOU7Fgg+h/8WyeVgo2MSf1juMdbVHpowlNGYpAx7UdkEx8NJcBGMW/HAnvpI7HPs7NWrrjpG6U+PDPWuMGUuDU8tpVSXEtj9pQKBgCujJousy9j7Ix5/HDalKLYJuW2nSO92bw6aOKfEhG8Eg8he3T68VNHoVC7EQmcn0GLd0EoW6MdeF5S+7UOAcQ2zguW57aKWdfDBMhMTFAuAIGxnnAn/igQ3VDsCgKaCH9S3ipxuZYw0O2noGY93kXnsgj3CMSY8PH458DK/BkRi";
    String merchKey = "QHywBp3sujVYaVKgnEnVJajGJ5N4F7SIq9Xowd8vRMOZWwTMfV3/11PVapuz46rcZNI2E5RAxl4=";
    String key = "nTSHsXhwLmoKgZSWf4gCAZTp3mTAyUGQWbZhHmJSSd9i886ZLwtBQLVRbYej/L0SEc+RxFZDEbowhiSTrm2+/8pRWG/r3SS1cgXQ7lv6R4ZcEudecZyAjnL5tIILbHDt+eNUr44wjRJixuz+UKFTiw==";
    public String pay(String orderId, BigDecimal transAmt, String clientIp, String notifyUrl, String frontUrl) {
        JSONObject body1 = new JSONObject();
        body1.put("mallOrderCode",orderId);
        body1.put("receiveAddress",orderId);
        body1.put("goodsDesc",orderId);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderCode",orderId);
        jsonObject.put("body",orderId);
        jsonObject.put("subject","虚拟商品");
        //jsonObject.put("payMode","sand_upsdk");
        //jsonObject.put("clientIp","117.136.40.57");
        jsonObject.put("clientIp",clientIp);
        jsonObject.put("totalAmount",String.format("%012d",transAmt.longValue()));
        jsonObject.put("payTool","0401");
        //jsonObject.put("payModeList","[alipay]");
        //jsonObject.put("notifyUrl","http://api.gzjiezo.com/action");
        jsonObject.put("notifyUrl",notifyUrl);
        jsonObject.put("frontUrl",frontUrl);
        jsonObject.put("extend","");
        JSONObject data = new JSONObject();
        data.put("body",jsonObject);
        data.put("head",getBaseEntity("sandpay.trade.precreate"));
        //data.put("head",getBaseEntity("sandpay.trade.pay"));
        //data.put("head",getBaseEntity("sandpay.trade.orderCreate"));
        String body = JSON.toJSONString(data);
        String sign = null;
        try {
            sign = RSAUtils.signBase64(body.getBytes("UTF-8"),privateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info(orderId);
        log.info(body);
        log.info(sign);
        Map<String,String> request = new HashMap<>();
        request.put("charset","utf-8");
        request.put("data",body);
        request.put("signType","01");
        request.put("extend","");
        request.put("sign",sign);
        //String response = HttpUtils.doPost(queryUrl,createRequest(request));
        String result = null;
        Map<String,String> respMap = new HashMap<>();
        String dataString = null;
        try {
            result = HttpClient.doPost(createUrl,request,connectTimeout,readTimeout);
            result = URLDecoder.decode(result, "utf-8");
            respMap = SDKUtil.convertResultStringToMap(result);
             dataString = respMap.get("data");

        } catch (IOException e) {
            e.printStackTrace();
            throw new BizException("请求失败");
        }
        log.info(result);
        log.info(dataString);
        return dataString;
    }
    public BaseEntity getBaseEntity(String method){
        return BaseEntity.builder()
                .version("1.0")
                .accessType("1")
                .method(method)
                .channelType("08")
                .productId("00002022")
                .mid(merchId)
                .reqTime(Kits.Date.getyyyyMMddHHmmss())
                .build();
    }
    public String orderQuery(String orderId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderCode",orderId);
        jsonObject.put("extend","");
        JSONObject data = new JSONObject();
        data.put("body",jsonObject);
        data.put("head",getBaseEntity("sandpay.trade.query"));
        String body = JSON.toJSONString(data);
        String sign = null;
        try {
             sign = RSAUtils.signBase64(body.getBytes("UTF-8"),privateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info(body);
        log.info(sign);
        Map<String,String> request = new HashMap<>();
        request.put("charset","utf-8");
        request.put("data",body);
        request.put("signType","01");
        request.put("extend","");
        request.put("sign",sign);
        ////String response = HttpUtils.doPost(queryUrl,createRequest(request));
        String result = null;
        String dataString = null;
        try {
            result = HttpClient.doPost(queryUrl,request,connectTimeout,readTimeout);
            result = URLDecoder.decode(result, "utf-8");
            Map<String, String> respMap = SDKUtil.convertResultStringToMap(result);
            dataString = respMap.get("data");

        } catch (IOException e) {
            throw new BizException("请求失败");
        }
        log.info(dataString);
        return dataString;
    }
    public String daifu(String orderId,String accNo,String accName,Long transAmt,String tranTime) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("version","01");
        jsonObject.put("productId","00000004");
        jsonObject.put("tranTime",tranTime);
        jsonObject.put("orderCode",orderId);
        jsonObject.put("extend","");
        jsonObject.put("currencyCode","156");
        jsonObject.put("accAttr","0");
        jsonObject.put("accType","4");
        jsonObject.put("remark","sett");
        jsonObject.put("accNo",accNo);
        jsonObject.put("accName",accName);
        jsonObject.put("tranAmt",String.format("%012d",transAmt.longValue()));

        String reqData = JSON.toJSONString(jsonObject);
        String sign = null;
        String encryptData  = null;
        String encryptKey  = null;
        try{
            String aesKey = Kits.Random.getRandomLetters(16);
            encryptData = AESTool.encryptBase64AesECBPkcs5Padding(reqData,aesKey);
            sign = RSAUtils.signBase64(reqData.getBytes("UTF-8"),privateKey);
            encryptKey = Base64.encode(RSAUtils.encryptByPublicKeyRsaECBPacs1Padding(aesKey.getBytes("UTF-8"),publicKey));
        }catch (Exception e){

        }
        Map<String, String> reqMap = new HashMap<String, String>();
        //整体报文格式
        reqMap.put("transCode", "RTPM"); // 交易码
        reqMap.put("accessType", "0"); // 接入类型
        reqMap.put("merId", merchId); // 合作商户ID	杉德系统分配，唯一标识
        reqMap.put("encryptKey", encryptKey); // 加密后的AES秘钥
        reqMap.put("encryptData", encryptData); // 加密后的请求/应答报文
        reqMap.put("sign", sign); // 签名
        reqMap.put("extend", ""); // 扩展域
        String result = null;
        String dataString = null;
        try {
            result = HttpClient.doPost(agentPayUrl,reqMap,connectTimeout,readTimeout);
            result = URLDecoder.decode(result, "utf-8");
            Map<String, String> respMap = SDKUtil.convertResultStringToMap(result);
            dataString = respMap.get("data");
            String retEncryptKey = (String)respMap.get("encryptKey");
            String retEncryptData = (String)respMap.get("encryptData");
            String retSign = (String)respMap.get("sign");
            String key = RSAUtils.decryptByPrivateKeyRsaECBPacs1Padding(retEncryptKey,privateKey);
            dataString = AESTool.decryptBase64ECBPACK5Padding(retEncryptData,key);
        } catch (IOException e) {
            throw new BizException("请求失败");
        }catch (Exception e){

        }
        log.info(dataString);
        return dataString;
    }
    public String dfQuery(String orderId,String tranTime) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("version","01");
        jsonObject.put("productId","00000004");
        jsonObject.put("tranTime",tranTime);
        jsonObject.put("orderCode",orderId);
        jsonObject.put("extend","");
        String reqData = JSON.toJSONString(jsonObject);
        String sign = null;
        String encryptData  = null;
        String encryptKey  = null;
        try{
            String aesKey = Kits.Random.getRandomLetters(16);
            encryptData = AESTool.encryptBase64AesECBPkcs5Padding(reqData,aesKey);
            sign = RSAUtils.signBase64(reqData.getBytes("UTF-8"),privateKey);
            encryptKey = Base64.encode(RSAUtils.encryptByPublicKeyRsaECBPacs1Padding(aesKey.getBytes("UTF-8"),publicKey));
        }catch (Exception e){

        }
        Map<String, String> reqMap = new HashMap<String, String>();
        //整体报文格式
        reqMap.put("transCode", "ODQU"); // 交易码
        reqMap.put("accessType", "0"); // 接入类型
        reqMap.put("merId", merchId); // 合作商户ID	杉德系统分配，唯一标识
        reqMap.put("encryptKey", encryptKey); // 加密后的AES秘钥
        reqMap.put("encryptData", encryptData); // 加密后的请求/应答报文
        reqMap.put("sign", sign); // 签名
        reqMap.put("extend", ""); // 扩展域
        String result = null;
        String dataString = null;
        try {
            result = HttpClient.doPost(dfQueryUrl,reqMap,connectTimeout,readTimeout);
            result = URLDecoder.decode(result, "utf-8");
            Map<String, String> respMap = SDKUtil.convertResultStringToMap(result);
            dataString = respMap.get("data");
            String retEncryptKey = (String)respMap.get("encryptKey");
            String retEncryptData = (String)respMap.get("encryptData");
            String retSign = (String)respMap.get("sign");
            String key = RSAUtils.decryptByPrivateKeyRsaECBPacs1Padding(retEncryptKey,privateKey);
            dataString = AESTool.decryptBase64ECBPACK5Padding(retEncryptData,key);
        } catch (IOException e) {
            throw new BizException("请求失败");
        }catch (Exception e){

        }
        log.info(dataString);
        return dataString;
    }
    public String balanceQuery(String orderId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("version","01");
        jsonObject.put("productId","00000004");
        jsonObject.put("tranTime",Kits.Date.getyyyyMMddHHmmss());
        jsonObject.put("orderCode",orderId);
        jsonObject.put("channelType","");
        jsonObject.put("extend","");
        String reqData = JSON.toJSONString(jsonObject);
        String sign = null;
        String encryptData  = null;
        String encryptKey  = null;
        try{
            String aesKey = Kits.Random.getRandomLetters(16);
            encryptData = AESTool.encryptBase64AesECBPkcs5Padding(reqData,aesKey);
            sign = RSAUtils.signBase64(reqData.getBytes("UTF-8"),privateKey);
            encryptKey = Base64.encode(RSAUtils.encryptByPublicKeyRsaECBPacs1Padding(aesKey.getBytes("UTF-8"),publicKey));
        }catch (Exception e){

        }
        Map<String, String> reqMap = new HashMap<String, String>();
        //整体报文格式
        reqMap.put("transCode", "MBQU"); // 交易码
        reqMap.put("accessType", "0"); // 接入类型
        reqMap.put("merId", merchId); // 合作商户ID	杉德系统分配，唯一标识
        reqMap.put("encryptKey", encryptKey); // 加密后的AES秘钥
        reqMap.put("encryptData", encryptData); // 加密后的请求/应答报文
        reqMap.put("sign", sign); // 签名
        reqMap.put("extend", ""); // 扩展域
        String result = null;
        String dataString = null;
        try {
            result = HttpClient.doPost(queryBalanceUrl,reqMap,connectTimeout,readTimeout);
            result = URLDecoder.decode(result, "utf-8");
            Map<String, String> respMap = SDKUtil.convertResultStringToMap(result);
            dataString = respMap.get("data");
            String retEncryptKey = (String)respMap.get("encryptKey");
            String retEncryptData = (String)respMap.get("encryptData");
            String retSign = (String)respMap.get("sign");
            String key = RSAUtils.decryptByPrivateKeyRsaECBPacs1Padding(retEncryptKey,privateKey);
            dataString = AESTool.decryptBase64ECBPACK5Padding(retEncryptData,key);
        } catch (IOException e) {
            throw new BizException("请求失败");
        }catch (Exception e){

        }
        log.info(dataString);
        return dataString;
    }
    public static String createRequest(Map<String, String> parm) {
        StringBuffer rtn = new StringBuffer();
        for (String s : parm.keySet()) {
            try {
                if (parm.get(s) != null) {
                    rtn.append(s).append("=").append(URLEncoder.encode(parm.get(s), "UTF-8")).append("&");
                    //rtn.append(s).append("=").append(parm.get(s).toString()).append("&");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return rtn.toString();
    }

    public String payH5(String orderId, BigDecimal transAmt, String clientIp, String notifyUrl, String frontUrl) {
        JSONObject body1 = new JSONObject();
        body1.put("mer_app_id","");
        body1.put("openid","");
        body1.put("buyer_id","");
        body1.put("wx_app_id","");
        body1.put("gh_ori_id","");
        body1.put("path_url","");
        body1.put("miniProgramType","");

        clientIp = clientIp.replace(".", "_");

        Map paramMap = new HashMap<String, String>();
        paramMap.put("version","10");
        paramMap.put("mer_no",merchId);
        paramMap.put("mer_key", merchKey);
        paramMap.put("mer_order_no",orderId);
        paramMap.put("create_time", Kits.Date.getyyyyMMddHHmmss());
        paramMap.put("expire_time", getNextDayTime());
        paramMap.put("order_amt",transAmt.toString());
        paramMap.put("notify_url",notifyUrl);
        paramMap.put("return_url",frontUrl);
        paramMap.put("create_ip", clientIp);
        paramMap.put("goods_name","好家伙");
        paramMap.put("store_id","000000");
        paramMap.put("product_code", "02020004");
        paramMap.put("clear_cycle", "3");
        paramMap.put("pay_extra", body1.toJSONString());
        paramMap.put("accsplit_flag","NO");
        paramMap.put("jump_scheme","sandcash://scpay");
        paramMap.put("sign_type","MD5");

        String stringSignTemp= "accsplit_flag="+paramMap.get("accsplit_flag")+
                        "&create_ip="+paramMap.get("create_ip")+
                        "&create_time="+paramMap.get("create_time")+
                        "&mer_key="+paramMap.get("mer_key")+
                        "&mer_no="+paramMap.get("mer_no")+
                        "&mer_order_no="+paramMap.get("mer_order_no")+
                        "&notify_url="+paramMap.get("notify_url")+
                        "&order_amt="+paramMap.get("order_amt")+
                        "&pay_extra="+paramMap.get("pay_extra")+
                        "&return_url="+paramMap.get("return_url")+
                        "&sign_type="+paramMap.get("sign_type")+
                        "&store_id="+paramMap.get("store_id")+
                        "&version="+paramMap.get("version")+"&key="+key+"";
        System.out.println(stringSignTemp);
        String sign = null;
        try {
            sign =  Md5Utils.getMd5(stringSignTemp).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info(orderId);
        log.info(sign);

        //String response = HttpUtils.doPost(queryUrl,createRequest(request));
        /*
        String result = null;
        Map<String,String> respMap = new HashMap<>();
        String dataString = null;
        try {
            result = HttpClient.doPost("https://sandpay.alipay.trade.jsapi.pay.vapp",paramMap,connectTimeout,readTimeout);
            result = URLDecoder.decode(result, "utf-8");
            respMap = SDKUtil.convertResultStringToMap(result);
            dataString = respMap.get("data");

        } catch (IOException e) {
            e.printStackTrace();
            throw new BizException("请求失败");
        }
        log.info(result);
        log.info(dataString);*/
        return sign;
    }

    public static String getNextDayTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        return new SimpleDateFormat("yyyyMMddHHmmss").format(calendar.getTime());
    }
    public static void main(String[] args) {
        System.out.println(Kits.Date.getyyyyMMddHHmmss(SystemClockUtil.getDate().getTime()));
        SandeService sandeService = new SandeService();
        //sandeService.daifu("O20200925192912Q1zu","1","1",100L);
        //sandeService.balanceQuery(BaseUtils.createOrderId());
        //sandeService.balanceQuery("O20200925192912Q1zu");
        sandeService.payH5(Kits.Date.getyyyyMMddHHmmss(SystemClockUtil.getDate().getTime()), new BigDecimal(100), "", "http://renrenpin.shop/#/pages/my/order/order?idx=0", "http://renrenpin.shop/#/pages/my/order/order?idx=0");
    }


}
